package lizhe;

/**
 * 旋转数组
 * 给定一个整数数组 nums，将数组中的元素向右轮转 k 个位置，其中 k 是非负数。
 * <p>
 * 输入: nums = [1,2,3,4,5,6,7], k = 3
 * 输出: [5,6,7,1,2,3,4]
 * 解释:
 * 向右轮转 1 步: [7,1,2,3,4,5,6]
 * 向右轮转 2 步: [6,7,1,2,3,4,5]
 * 向右轮转 3 步: [5,6,7,1,2,3,4]
 */
public class Rotate {
    public void rotate(int[] nums, int k) {
        if (k > nums.length - 1)
            k = k % nums.length;
        if (nums.length == 1 || k == 0)
            return;
        flip(nums, 0, nums.length - 1);
        flip(nums, 0, k - 1);
        flip(nums, k, nums.length - 1);

    }

    private void flip(int[] nums, int start, int end) {
        int i = 0;
        int tmp;
        while (i < 1 + (end - start) / 2) {
            tmp = nums[end - i];
            nums[end - i] = nums[start + i];
            nums[start + i] = tmp;
            i++;
        }
    }

    public static void main(String[] args) {
        Rotate rotate = new Rotate();
        int[] arr = {1, 2, 3};
        rotate.rotate(arr, 3);
        System.out.println("");
    }
}
